<template>
  <div class="review-step">
    <a-tabs v-model:activeKey="activeTab">
      <a-tab-pane key="code-review" tab="代码评审">
        <a-row :gutter="16">
          <a-col :span="12">
            <div class="review-section">
              <h3>待评审代码</h3>
              <a-tree
                :tree-data="codeTree"
                :selected-keys="selectedCodeKeys"
                @select="handleCodeSelect"
              >
                <template #title="{ title }">
                  <span>{{ title }}</span>
                </template>
              </a-tree>
            </div>
          </a-col>
          <a-col :span="12">
            <div class="review-section">
              <h3>代码详情</h3>
              <div v-if="selectedCode" class="code-detail">
                <div class="code-header">
                  <span class="filename">{{ selectedCode.name }}</span>
                  <a-tag color="blue">{{ selectedCode.language }}</a-tag>
                  <a-button type="link" size="small" @click="viewFullCode">查看完整文件</a-button>
                </div>
                <pre class="code-content">{{ selectedCode.content }}</pre>
                
                <div class="review-comments">
                  <h4>评审意见 ({{ comments.length }})</h4>
                  <div v-for="comment in comments" :key="comment.id" class="comment-item">
                    <a-comment>
                      <template #author>
                        <a>{{ comment.author }}</a>
                      </template>
                      <template #avatar>
                        <a-avatar :src="comment.avatar" />
                      </template>
                      <template #content>
                        <p>{{ comment.content }}</p>
                      </template>
                      <template #datetime>
                        <a-tooltip :title="formatTime(comment.time)">
                          <span>{{ fromNow(comment.time) }}</span>
                        </a-tooltip>
                      </template>
                    </a-comment>
                  </div>
                  
                  <a-textarea
                    v-model:value="newComment"
                    placeholder="添加评审意见"
                    :rows="4"
                  />
                  <div class="comment-actions">
                    <a-button type="primary" @click="addComment">提交意见</a-button>
                    <a-button style="margin-left: 10px" @click="newComment = ''">取消</a-button>
                  </div>
                </div>
              </div>
              <div v-else class="empty-tip">
                <a-empty description="请从左侧选择代码文件" />
              </div>
            </div>
          </a-col>
        </a-row>
      </a-tab-pane>
      
      <a-tab-pane key="design-review" tab="设计评审">
        <div class="design-review">
          <a-row :gutter="16">
            <a-col :span="12">
              <div class="design-documents">
                <h3>设计文档</h3>
                <a-list
                  :data-source="designDocuments"
                  :pagination="{ pageSize: 5 }"
                >
                  <template #renderItem="{ item }">
                    <a-list-item>
                      <a-list-item-meta
                        :description="`更新于 ${formatTime(item.updatedAt)}`"
                      >
                        <template #title>
                          <a @click="viewDesignDocument(item)">{{ item.name }}</a>
                        </template>
                        <template #avatar>
                          <file-text-outlined style="font-size: 24px" />
                        </template>
                      </a-list-item-meta>
                    </a-list-item>
                  </template>
                </a-list>
              </div>
            </a-col>
            <a-col :span="12">
              <div class="design-comments">
                <h3>设计评审意见</h3>
                <div v-if="selectedDesignDoc" class="design-doc-comments">
                  <h4>{{ selectedDesignDoc.name }}</h4>
                  <a-comment
                    v-for="comment in designComments"
                    :key="comment.id"
                    :author="comment.author"
                    :avatar="comment.avatar"
                    :content="comment.content"
                    :datetime="fromNow(comment.time)"
                  />
                  
                  <a-textarea
                    v-model:value="newDesignComment"
                    placeholder="添加设计评审意见"
                    :rows="4"
                  />
                  <div class="comment-actions">
                    <a-button type="primary" @click="addDesignComment">提交意见</a-button>
                    <a-button style="margin-left: 10px" @click="newDesignComment = ''">取消</a-button>
                  </div>
                </div>
                <div v-else class="empty-tip">
                  <a-empty description="请从左侧选择设计文档" />
                </div>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-tab-pane>
      
      <a-tab-pane key="review-summary" tab="评审总结">
        <div class="review-summary">
          <a-descriptions bordered :column="2">
            <a-descriptions-item label="代码评审完成率">{{ reviewStats.codeReviewCompleted }}%</a-descriptions-item>
            <a-descriptions-item label="设计评审完成率">{{ reviewStats.designReviewCompleted }}%</a-descriptions-item>
            <a-descriptions-item label="发现问题数">{{ reviewStats.issuesFound }}</a-descriptions-item>
            <a-descriptions-item label="严重问题数">{{ reviewStats.criticalIssues }}</a-descriptions-item>
            <a-descriptions-item label="评审参与人数">{{ reviewStats.participants }}</a-descriptions-item>
            <a-descriptions-item label="平均评审时间">{{ reviewStats.avgReviewTime }}小时</a-descriptions-item>
          </a-descriptions>
          
          <a-divider />
          
          <h3>评审结论</h3>
          <a-radio-group v-model:value="reviewConclusion" class="conclusion-radio">
            <a-radio-button value="approved">通过</a-radio-button>
            <a-radio-button value="approved-with-conditions">有条件通过</a-radio-button>
            <a-radio-button value="rejected">不通过</a-radio-button>
          </a-radio-group>
          
          <a-textarea
            v-model:value="conclusionComment"
            placeholder="请输入评审结论说明"
            :rows="4"
            class="conclusion-textarea"
          />
          
          <div class="summary-actions">
            <a-button type="primary" @click="submitReview">提交评审结果</a-button>
            <a-button style="margin-left: 10px" @click="saveDraft">保存草稿</a-button>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>
    
    <!-- 完整代码查看模态框 -->
    <a-modal
      v-model:open="codeModal.visible"
      :title="codeModal.title"
      width="90%"
      :footer="null"
    >
      <div class="full-code-viewer">
        <pre class="code-content">{{ codeModal.content }}</pre>
      </div>
    </a-modal>
    
    <!-- 设计文档查看模态框 -->
    <a-modal
      v-model:open="designModal.visible"
      :title="designModal.title"
      width="80%"
      :footer="null"
    >
      <div class="design-doc-viewer">
        <div v-if="designModal.type === 'image'" class="design-image">
          <a-image :src="designModal.content" />
        </div>
        <div v-else-if="designModal.type === 'pdf'" class="design-pdf">
          <iframe :src="designModal.content" width="100%" height="600px"></iframe>
        </div>
        <div v-else class="design-text">
          <pre>{{ designModal.content }}</pre>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { FileTextOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

const props = defineProps({
  stepData: Object
});

const emit = defineEmits(['update']);

const activeTab = ref('code-review');

// 代码评审相关
const codeTree = ref([
  {
    key: 'src',
    title: 'src',
    children: [
      {
        key: 'src/components',
        title: 'components',
        children: [
          { key: 'src/components/LoginForm.vue', title: 'LoginForm.vue', isLeaf: true },
          { key: 'src/components/UserList.vue', title: 'UserList.vue', isLeaf: true }
        ]
      },
      {
        key: 'src/views',
        title: 'views',
        children: [
          { key: 'src/views/Home.vue', title: 'Home.vue', isLeaf: true },
          { key: 'src/views/Profile.vue', title: 'Profile.vue', isLeaf: true }
        ]
      },
      { key: 'src/main.js', title: 'main.js', isLeaf: true }
    ]
  },
  {
    key: 'public',
    title: 'public',
    children: [
      { key: 'public/index.html', title: 'index.html', isLeaf: true }
    ]
  }
]);

const codeFiles = {
  'src/components/LoginForm.vue': {
    name: 'LoginForm.vue',
    language: 'Vue',
    content: `<template>
  <div class="login-form">
    <a-form :model="form" @submit="handleSubmit">
      <a-form-item label="用户名">
        <a-input v-model:value="form.username" />
      </a-form-item>
      <a-form-item label="密码">
        <a-input-password v-model:value="form.password" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    handleSubmit() {
      // 登录逻辑
    }
  }
}
</script>`
  },
  'src/views/Home.vue': {
    name: 'Home.vue',
    language: 'Vue',
    content: `<template>
  <div class="home">
    <h1>欢迎页面</h1>
    <p>这里是系统首页</p>
  </div>
</template>

<script>
export default {
  name: 'Home'
}
</script>`
  }
};

const selectedCodeKeys = ref([]);
const selectedCode = ref(null);
const comments = ref([
  {
    id: 1,
    author: '张三',
    avatar: 'https://randomuser.me/api/portraits/men/1.jpg',
    content: '建议将登录逻辑提取到单独的auth模块中',
    time: new Date('2023-05-18 10:30:00')
  },
  {
    id: 2,
    author: '李四',
    avatar: 'https://randomuser.me/api/portraits/men/2.jpg',
    content: '密码输入框需要添加显示/隐藏密码的功能',
    time: new Date('2023-05-18 11:15:00')
  }
]);
const newComment = ref('');

// 设计评审相关
const designDocuments = ref([
  {
    id: 1,
    name: '用户认证模块设计',
    type: 'pdf',
    content: 'https://example.com/design1.pdf',
    updatedAt: new Date('2023-05-10 14:30:00')
  },
  {
    id: 2,
    name: '数据库ER图',
    type: 'image',
    content: 'https://example.com/er-diagram.png',
    updatedAt: new Date('2023-05-12 09:15:00')
  },
  {
    id: 3,
    name: 'API接口文档',
    type: 'text',
    content: 'API接口设计文档内容...',
    updatedAt: new Date('2023-05-15 16:45:00')
  }
]);

const selectedDesignDoc = ref(null);
const designComments = ref([]);
const newDesignComment = ref('');

// 评审总结相关
const reviewStats = reactive({
  codeReviewCompleted: 75,
  designReviewCompleted: 90,
  issuesFound: 12,
  criticalIssues: 3,
  participants: 5,
  avgReviewTime: 2.5
});

const reviewConclusion = ref('approved');
const conclusionComment = ref('');

// 模态框相关
const codeModal = reactive({
  visible: false,
  title: '',
  content: ''
});

const designModal = reactive({
  visible: false,
  title: '',
  content: '',
  type: ''
});

const formatTime = (date) => {
//   return format(date, 'yyyy-MM-dd HH:mm');
};

const fromNow = (date) => {
//   return formatDistanceToNow(date, { addSuffix: true });
};

const handleCodeSelect = (selectedKeys) => {
  selectedCodeKeys.value = selectedKeys;
  if (selectedKeys.length > 0) {
    const fileKey = selectedKeys[0];
    selectedCode.value = codeFiles[fileKey] || null;
  } else {
    selectedCode.value = null;
  }
};

const viewFullCode = () => {
  if (selectedCode.value) {
    codeModal.title = selectedCode.value.name;
    codeModal.content = selectedCode.value.content;
    codeModal.visible = true;
  }
};

const addComment = () => {
  if (!newComment.value.trim()) {
    message.warning('请输入评审意见');
    return;
  }
  
  comments.value.push({
    id: Date.now(),
    author: '当前用户',
    avatar: 'https://randomuser.me/api/portraits/men/3.jpg',
    content: newComment.value,
    time: new Date()
  });
  
  newComment.value = '';
  message.success('评审意见已添加');
};

const viewDesignDocument = (doc) => {
  selectedDesignDoc.value = doc;
  designComments.value = [
    {
      id: 1,
      author: '王五',
      avatar: 'https://randomuser.me/api/portraits/men/4.jpg',
      content: '数据库设计需要增加用户操作日志表',
      time: new Date('2023-05-16 14:20:00')
    }
  ];
  
  // 如果是文本内容，直接显示在模态框
  if (doc.type === 'text') {
    designModal.title = doc.name;
    designModal.content = doc.content;
    designModal.type = 'text';
    designModal.visible = true;
  }
};

const addDesignComment = () => {
  if (!newDesignComment.value.trim()) {
    message.warning('请输入设计评审意见');
    return;
  }
  
  designComments.value.push({
    id: Date.now(),
    author: '当前用户',
    avatar: 'https://randomuser.me/api/portraits/men/3.jpg',
    content: newDesignComment.value,
    time: new Date()
  });
  
  newDesignComment.value = '';
  message.success('设计评审意见已添加');
};

const submitReview = () => {
  if (!conclusionComment.value.trim()) {
    message.warning('请输入评审结论说明');
    return;
  }
  
  const result = {
    conclusion: reviewConclusion.value,
    comment: conclusionComment.value,
    codeReviewComments: comments.value,
    designReviewComments: designComments.value
  };
  
  emit('update', { reviewResult: result });
  message.success('评审结果已提交');
};

const saveDraft = () => {
  const draft = {
    codeReviewComments: comments.value,
    designReviewComments: designComments.value,
    conclusion: reviewConclusion.value,
    conclusionComment: conclusionComment.value
  };
  
  emit('update', { reviewDraft: draft });
  message.success('评审草稿已保存');
};
</script>

<style scoped>
.review-step {
  padding: 10px;
}

.review-section {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  height: calc(100vh - 250px);
  overflow-y: auto;
}

.code-detail {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.code-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.code-header .filename {
  font-weight: bold;
  margin-right: 10px;
}

.code-content {
  flex: 1;
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow: auto;
  font-family: monospace;
  white-space: pre-wrap;
}

.review-comments {
  margin-top: 15px;
}

.comment-item {
  margin-bottom: 15px;
}

.comment-actions {
  margin-top: 10px;
  text-align: right;
}

.empty-tip {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.design-review {
  padding: 10px;
}

.design-documents {
  height: calc(100vh - 250px);
  overflow-y: auto;
}

.design-comments {
  height: calc(100vh - 250px);
  overflow-y: auto;
}

.design-doc-comments {
  height: 100%;
}

.review-summary {
  padding: 15px;
}

.conclusion-radio {
  margin: 15px 0;
  width: 100%;
}

.conclusion-radio :deep(.ant-radio-button-wrapper) {
  width: 33.33%;
  text-align: center;
}

.conclusion-textarea {
  margin-bottom: 15px;
}

.summary-actions {
  text-align: right;
}

.full-code-viewer {
  height: 70vh;
  overflow: auto;
}

.full-code-viewer .code-content {
  height: 100%;
}

.design-doc-viewer {
  height: 70vh;
  overflow: auto;
}

.design-image img {
  max-width: 100%;
}

.design-text pre {
  white-space: pre-wrap;
  font-family: monospace;
}
</style>